import type { Store } from "pinia";
import { reactive } from "vue";

export type ApiMethod<T> =(params:any)=> Promise<Axios.List<T>>;
export class ListMixins<T>{
	public list: {
		data: T[];
		page: number;
		size: number;
		total: number;
		loading: boolean;
	};
	public query:{[x:string]:any}

	protected api: ApiMethod<T>;

	constructor(args:{api:ApiMethod<T>,size?:number}){
		this.api=args.api;
		this.list=reactive({
			data:[],
			page: 1,
			size: args.size||20,
			total: 0,
			loading: false
		})
	}

	public async getData():Promise<Axios.List<T>>{
		let { page, size} = this.list;
		let query= this.query
		this.list.loading = true;
		return new Promise((resolve,reject)=>{
			this.api({
				page,
				size,
				...query
			}).then(res=>{
				this.list.data = res.data.list;
				this.list.total = res.data.total;
				resolve(res)
			}).catch(reject)
			.finally(()=>{
				this.list.loading = false;
			});
		})

	}

	public pageChange(e:number){
		this.list.page=e;
		this.getData()
	}

	public sizeChange(e:number){
		this.list.size=e;
		this.getData()
	}

	// public resetQuery(){
	// 	this.list.page=1
	// 	this.query={}
	// 	this.getData()
	// }
}
